import axios from 'axios'
import { Message } from 'element-ui'
import cookie from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 12000 // 请求超时时间
})

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

// // http request 拦截器
service.interceptors.request.use(
  config => {
    //当cookie中获取到了token信息时，则将token放在header中随请求发送给服务器接口
    if (cookie.get('yinzhi_jwt_token')) {
      config.headers['token'] = cookie.get('yinzhi_jwt_token')
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
       * code为非0是抛错
       */
    const res = response.data
    if(res.code === 0) {//返回正确结果
      return response.data
    } else if (res.code === 11002) {//获取用户信息失败
      //清除cookie
      cookie.set('yinzhi_jwt_token', '', { domain: 'localhost'})
      return response.data
    } else if (res.code === 10999) {//鉴权失败
        window.location.href = '/#/login'
        return
    } else {//其他错误结果
      Message({
        message: res.msg || 'error',
        type: 'error',
        duration: 5 * 1000
      })

      return Promise.reject('error')
    }
  },
  error => {
    console.log('err：' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
